iT邦幫忙

2025 iThome 鐵人賽

DAY 11
0
Modern Web

Laravel 30天速成筆記系列 第 11

【Day11】Model 關聯(One-to-One、One-to-Many)

  • 分享至 

  • xImage
  •  

在資料庫設計中,不同資料表之間通常會有關聯關係,前幾天介紹的Eloquent ORM 幫我們簡化了這些關聯的操作,讓你不必自己手寫複雜的 SQL!接下來今天我們要認識 一對一(One-to-One)一對多(One-to-Many)


一對一(One-to-One)

什麼是一對一?

  • 一個User有一張個人資料(Profile)
  • 一張個人資料只屬於一個User

資料表設計:

  • users 表:存放使用者基本資料
  • profiles 表:多一個 user_id 外鍵
// migration for profiles
Schema::create('profiles', function (Blueprint $table) {
    $table->id();
    $table->foreignId('user_id')->constrained()->onDelete('cascade');
    $table->string('phone');
    $table->string('address');
    $table->timestamps();
});

Model 寫法

// User.php
public function profile()
{
    return $this->hasOne(Profile::class);
}

// Profile.php
public function user()
{
    return $this->belongsTo(User::class);
}

該如何運用??

// 取得User的個人資料
$user = User::find(1);
$profile = $user->profile;

// 取得個人資料對應的使用者
$profile = Profile::find(1);
$user = $profile->user;

一對多(One-to-Many)

什麼是一對多?

  • 一篇文章(Post)有多則留言(Comment)
  • 每則留言只屬於一篇文章

資料表設計:

  • posts
  • comments 表:多一個 post_id 外鍵
// migration for comments
Schema::create('comments', function (Blueprint $table) {
    $table->id();
    $table->foreignId('post_id')->constrained()->onDelete('cascade');
    $table->text('content');
    $table->timestamps();
});

Model 寫法

// Post.php
public function comments()
{
    return $this->hasMany(Comment::class);
}

// Comment.php
public function post()
{
    return $this->belongsTo(Post::class);
}

該如何使用??

// 取得文章的所有留言
$post = Post::find(1);
$comments = $post->comments;

// 取得留言對應的文章
$comment = Comment::find(1);
$post = $comment->post;

小提醒(常見錯誤)!!

  1. 外鍵命名:Laravel 預設會找 表名稱_id(例如 user_idpost_id

  2. 外鍵約束:記得用 constrained() 建立關聯,資料一致性更好

  3. hasOne vs belongsTo

    • hasOne → 擁有關聯的一方(例如 User 有 Profile)
    • belongsTo → 屬於某一方的資料(例如 Profile 屬於 User)

小結

  • One-to-One:一對一關係(User ↔ Profile)
  • One-to-Many:一對多關係(Post ↔ Comments)
  • 在 Eloquent 中只要定義好關聯方法,就能用物件方式取得相關資料

上一篇
【Day10】Migration 進階篇
系列文
Laravel 30天速成筆記11
圖片
  熱門推薦
圖片
{{ item.channelVendor }} | {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言